<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../../styles/common.css"/>
    <link rel="stylesheet" href="../../../styles/page.css"/>
</head>
<body>
<div class="dashboard-container" id="sysUser-app">
    <div class="container">
        <div class="tableBar">
            <el-input
                    v-model="conditions.input"
                    placeholder="请输入用户名称"
                    style="width: 250px"
                    clearable
                    @keyup.enter.native="handleQuery"
            >
                <i
                        slot="prefix"
                        class="el-input__icon el-icon-search"
                        style="cursor: pointer"
                        @click="init"
                ></i>
            </el-input>
            <div class="tableLab">
                <el-button  type="primary" class="continue" @click="addClass('class')"> + 新增用户 </el-button>
            </div>
        </div>
        <el-table  :data="pagination.tableData"  stripe  class="tableBox" >
            <el-table-column prop="username" label="用户名称"></el-table-column>
            <el-table-column prop="email" label="用户邮箱"></el-table-column>
            <el-table-column prop="gender" label="性别">
                <template slot-scope="scope">
                    {{ String(scope.row.gender) === 'male' ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="telephone" label="电话"></el-table-column>
            <el-table-column prop="birthday" label="生日"></el-table-column>
            <el-table-column prop="salary" label="薪水"></el-table-column>
            <el-table-column prop="joinDate" label="入职日期"></el-table-column>
            <el-table-column label="账号状态">
                <template slot-scope="scope">
                    {{ String(scope.row.state) === '0' ? '已禁用' : '正常' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="160" align="center">
                <template slot-scope="scope">
                    <el-button type="text" size="small" class="blueBug" @click="editHandle(scope.row)">修改</el-button>
                    <span v-if="scope.row.state == 1">
                        <el-button type="text" size="small" class="delBut non" @click="deleteHandle(scope.row.id,0)">停用</el-button>
                    </span>
                    <span v-if="scope.row.state == 0 ">
                        <el-button type="text" size="small" class="delBut non" @click="deleteHandle(scope.row.id,1)">启用</el-button>
                    </span>
                    <el-button type="text" size="small" class="infoBut" @click="toUserRole(scope.row.id)">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                class="pageList"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.counts"
                @size-change="handleSizeChange"
                :current-page.sync="pagination.page"
                @current-change="handleCurrentChange">
        </el-pagination>
    </div>
    <el-dialog :title="classData.title" :visible.sync="classData.dialogVisible" width="30%" :before-close="handleClose">
        <el-form class="demo-form-inline" label-width="100px">

            <el-form-item label="账号：">
                <el-input v-model="classData.dialogForm.username" placeholder="请输入用户名称" maxlength="14" @blur="checkUsername()"/>
            </el-form-item>
            <span style="color:red">{{checkMessage}}</span>
            <el-form-item label="用户邮箱：">
                <el-input v-model="classData.dialogForm.email" placeholder="请输入用户邮箱" />
            </el-form-item>
            <el-form-item label="身份证号：">
                <el-input v-model="classData.dialogForm.station" placeholder="请输入身份证号" maxlength="14"/>
            </el-form-item>
            <el-form-item label="用户性别：">
                <template>
                    <el-radio v-model="classData.dialogForm.gender" label="male">男</el-radio>
                    <el-radio v-model="classData.dialogForm.gender" label="female">女</el-radio>
                </template>
            </el-form-item>
            <el-form-item label="用户电话：">
                <el-input v-model="classData.dialogForm.telephone" type="number" placeholder="请输入用户电话"/>
            </el-form-item>

            <el-form-item label="用户生日：">
                <el-date-picker
                        v-model="classData.dialogForm.birthday"
                        type="date"
                        format="yyyy-MM-dd"
                        placeholder="请选择用户生日">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="用户薪水：">
                <el-input v-model="classData.dialogForm.salary" type="number" placeholder="请输入用户薪水"/>
            </el-form-item>
            <el-form-item label="入职日期：">
                <el-date-picker
                        v-model="classData.dialogForm.joinDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择入职日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="备注：">
                <el-input v-model="classData.dialogForm.remark" type="number" placeholder="备注"/>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="classData.dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="userRole.title" :visible.sync="userRole.dialogVisible" width="30%" :before-close="userRoleClose">
        <el-form class="demo-form-inline" label-width="100px">
            <el-form-item label="角色：">
                <el-checkbox-group v-model="userRole.checkRoleIds">
                    <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="userRole.dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="updateUserRole()">确 定</el-button>
      </span>
    </el-dialog>
</div>
<script src="../../../plugins/vue/vue.js"></script>
<script src="../../../plugins/element-ui/index.js"></script>
<script src="../../../plugins/axios/axios.min.js"></script>
<script src="../../../js/request.js"></script>
<script src="../../../api/sysUser.js"></script>
<!--<script src="../../../api/sysRole.js"></script>-->
<script type="text/javascript">
    new Vue({
        el: '#sysUser-app',
        data() {
            return {
                action: '',
                type: '',
                roleList:[],
                userRole:{
                    'title': '分配角色',
                    'dialogVisible': false,
                    userId:'',
                    checkRoleIds:[]
                },
                classData: {
                    'title': '新增用户',
                    'dialogVisible': false,
                    dialogForm:{}
                },
                checkMessage:'',
                pagination:{
                    tableData: [],
                    page: 1,
                    pageSize: 5,
                    counts:0,
                },
                conditions:{
                    input:''
                }
            }
        },
        methods: {
            async init() {
                const params = {
                    page: this.pagination.page,//当前页码
                    pageSize: this.pagination.pageSize,//每页大小
                    name: this.conditions.input ? this.conditions.input : undefined//用户名称
                };
                await getUserPage(params).then(res => {
                    if (String(res.code) === '1') {
                        this.pagination.tableData = res.data.records;
                        this.pagination.counts = res.data.total;
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            handleQuery() {
                this.page = 1;
                this.init();
            },
            // 添加
            addClass(st) {
                this.classData.title = '新增用户';
                this.action = 'add';
                this.classData.dialogVisible = true
            },
            editHandle(dat) {
                //赋值
                this.classData.title = '修改用户';
                this.action = 'edit';
                this.classData.dialogForm = dat;
                console.log("dialogForm数据："+JSON.stringify(this.classData.dialogForm));
                this.classData.dialogVisible = true;//打开修改框
            },
            // 关闭弹窗
            handleClose(st) {
                this.classData.dialogVisible = false;
                this.classData.dialogForm = {};
                this.checkMessage = '';
            },
            // 关闭弹窗
            userRoleClose(st) {
                this.userRole.dialogVisible = false;
                this.userRole.checkRoleIds = [];
            },
            //删除
            deleteHandle(id,state) {
                this.$confirm('此操作将改变用户状态, 是否继续?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    const params = {
                        id: id,
                        state:state,
                    }
                    deleteUser(params).then(res => {
                        if (res.code === 1) {
                            this.$message.success('操作成功！');
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },
            //数据提交
            submitForm(st) {
                const classData = this.classData.dialogForm;
                const valid = (classData.name === 0 || classData.name) ;
                if (this.action === 'add') {
                        addUser(classData).then(res => {
                            if (res.code === 1) {
                                this.$message.success('添加成功！');
                                if (!st) {
                                    this.classData.dialogVisible = false;
                                } else {
                                    this.classData.dialogForm = {};
                                }
                                this.handleQuery();
                            } else {
                                this.$message.error(res.msg || '操作失败');
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err);
                        });
                } else if (this.action === 'edit') {
                    editUser(classData).then(res => {
                        if (res.code === 1) {
                                this.$message.success('修改成功！');
                                this.classData.dialogVisible = false;
                                this.classData.dialogForm={};
                                this.handleQuery();
                            } else {
                                this.$message.error(res.msg || '操作失败')
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err)
                        })

                } else {
                    this.$message.error('请输入名称');
                }
            },
            //检查用户名是否可用
            checkUsername(){
                const params = {
                    username: this.classData.dialogForm.username
                };
                console.log(params);
                checkUsername(params).then(res => {
                    if (res.code === 1) {
                        this.checkMessage = '';
                    } else {//此时code等于0
                        this.checkMessage = '用户名不能使用';
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            // 全部操作
            handleSelectionChange(val) {
                let checkArr = [];
                val.forEach((n) => {
                    checkArr.push(n.id)
                });
                this.checkList = checkArr
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.init()
            },
            handleCurrentChange(val) {
                this.page = val;
                this.init()
            },
            toUserRole(id){
                this.userRole.dialogVisible = true;
                this.userRole.checkRoleIds = [];
                //1.异步请求， 获取当前用户的角色列表
                findUserRoleList(id).then(res => {
                    if (String(res.code) === '1') {
                        this.userRole.checkRoleIds = res.data;
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                });
                //3.给userRole里的用户id赋值
                this.userRole.userId = id;
            },
            //更新用户角色
            updateUserRole(){
                const params = {
                    userId:this.userRole.userId,
                    roleIds:this.userRole.checkRoleIds
                };
                updateUserRole(params).then(res => {
                    if (String(res.code) === '1') {
                        this.$message.success('分配成功！');
                        this.userRole.dialogVisible = false;
                        this.userRole.checkRoleIds = [];
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                });
            },
            initRoleList(){
                findRoleList().then(res => {
                    if (String(res.code) === '1') {
                        this.roleList = res.data;
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                });
            }
        },
        created() {
            this.init();
            this.initRoleList();
        }
    })
</script>
</body>
</html>